<?php 

namespace app\applet\controller;

use app\applet\BaseController;
use app\library\wxprogram\WxDataCrypt;
use app\models\UserTokens;
use app\models\Wxprograms;
use think\facade\Db;


class UserController extends BaseController
{
	public function wxauthAction()
    {
        try{
            //获取用户信息
            $resData = $this->app->userService->getWxInfo($this->appletId, $this->post['code']);

            $user = $this->app->userService->getUserByOpenid($resData->openid);

            if (!$user) {
                throw new \Exception('用户未注册', 500);
            }

            $this->app->userService->saveSessionKey($user, $resData->session_key);
            $data = [
                'userId' => $user->userId,
                'userName' => $user->userName,
                'headImg' => $user->headImg,
                'openid' => $user->openid,
                'gender' => $user->gender,
                'totalCredit' => $user->totalCredit,
                'currentCredit' => $user->currentCredit,
                'donateCredit' => $user->donateCredit,
                'availCredit' => bcsub($user->totalCredit, $user->donateCredit),
                'sessionKey' => $user->sessionKey
            ];

            return json()->data(['code' => 200, 'msg' => '授权成功', 'data' => $data]);
        }catch(\Exception $e){
            return json()->data(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * @return \think\response\Json
     */
    public function wxloginAction()
    {
        Db::startTrans();
        try{
            //获取用户信息
            $resData = $this->app->userService->getWxInfo($this->appletId, $this->post['code']);

            $user = $this->app->userService->getUserByOpenid($resData->openid);
            if (!$user) {

                $data = [
                    'appletId' => $this->appletId,
                    'userName' => $this->post['userName'],
                    'headImg' => $this->post['headImg'],
                    'gender' => $this->post['gender'],
                    'openid' => $resData->openid,
                    'sessionKey' => $resData->session_key,
                    'totalCredit' => 0,
                    'currentCredit' => 0,
                    'donateCredit' => 0,
                ];

                if (isset($this->post['provinceName']) && $this->post['provinceName']) {
                    $province = $this->app->commonService->getProvinceByName($this->post['provinceName']);
                    $data['provinceCode'] = $province?$province->provinceCode:'';
                }

                if (isset($this->post['provinceName']) && $this->post['provinceName'] && isset($this->post['cityName']) && $this->post['cityName']) {
                    $city = $this->app->commonService->getCityByName($this->post['cityName'], $province->provinceId);
                    $data['cityCode'] = $city?$city->cityCode:'';
                }

                $user = $this->app->userService->addUser($data);
            }

            // 校验成功,组装TOKEN
            $token = $this->app->userService->makeToken($user->userId);
            Db::commit();

            $data = [
                'userId' => $user->userId,
                'userName' => $user->userName,
                'headImg' => $user->headImg,
                'openid' => $user->openid,
                'gender' => $user->gender,
                'totalCredit' => $user->totalCredit,
                'currentCredit' => $user->currentCredit,
                'donateCredit' => $user->donateCredit,
                'availCredit' => bcsub($user->totalCredit, $user->donateCredit),
                'token' => $token->token,
                'sessionKey' => $user->sessionKey,
            ];

            return json()->data(['code' => 200, 'msg' => '登录成功', 'data' => $data]);
        }catch(\Exception $e){
            Db::rollback();
            return json()->data(['code' => 500, 'msg' => $e->getMessage(),$e->getFile(),$e->getLine()]);
        }
    }

	/**
	 * [logoutAction 退出登录]
	 * function 
	 * @access
	 * @param  [type] [name]
	 * @return [type] [description]
	 */
	public function logoutAction()
	{
		try{
	        $token = UserTokens::where(['token' => $this->token])->find();
	        if ($token) {
	            $token->expireTime = date('Y-m-d H:i:s');
	            $token->status = UserTokens::STATUS_VAILD;
	            $token->save();
	        }
	        return json()->data(['code' => 200, 'msg' => '退出成功']);
	    }catch(\Exception $e){
	    	return json()->data(['code'=>$e->getCode(),"msg"=>$e->getMessage()]);
	    }
	}

    /**
     * @return \think\response\Json
     */
	public function detailAction()
	{
		try{
            if(!$this->user){
                throw new \Exception("请先登录",401);
            }

            $this->app->userService->createUniCode($this->user);

            $data = [
                'userId' => $this->user->userId,
                'userName' => $this->user->userName,
                'realName' => $this->user->realName,
                'phone' => $this->user->phone,
                'openid' => $this->user->openid,
                'gender' => $this->user->gender,
                'headImg' => $this->user->headImg,
                'universityId' => $this->user->universityId,
                'universityName' => $this->user->universityId?$this->user->university->universityName:'',
                'major' => $this->user->major,
                'year' => $this->user->year,
                'grade' => $this->user->grade,
                'gradeText' => $this->user->getGradeText(),
                'uniCode' => $this->user->uniCode,
                'totalCredit' => $this->user->totalCredit,
                'currentCredit' => $this->user->currentCredit,
                'donateCredit' => $this->user->donateCredit,
                'availCredit' => bcsub($this->user->totalCredit, $this->user->donateCredit),
                'sessionKey' => $this->user->sessionKey,
            ];

			return json()->data(['code' => 200, 'msg' => '',"data"=>$data]);

		}catch(\Exception $e){

			return json()->data(['code'=>$e->getCode(),"msg"=>$e->getMessage()]);
		}
	}

	public function updateAction()
    {
        try {
            if(!$this->user){
                throw new \Exception("请先登录",401);
            }

            if (isset($this->post['realName']) && $this->post['realName'] == '') {
                throw new \Exception('请填写姓名', 500);
            }

            if (isset($this->post['gender']) && $this->post['gender'] == '') {
                throw new \Exception('请填写性别', 500);
            }

            if (isset($this->post['phone']) && $this->post['phone'] == '') {
                throw new \Exception('请填写手机号', 500);
            }

            if (isset($this->post['universityId']) && $this->post['universityId'] == '') {
                throw new \Exception('请填写院校', 500);
            }

            if (isset($this->post['year']) && $this->post['year'] == '') {
                throw new \Exception('请填写入学年份', 500);
            }

            if (isset($this->post['major']) && $this->post['major'] == '') {
                throw new \Exception('请填写院系', 500);
            }

            $this->app->userService->update($this->user, $this->post);

            return json()->data(['code' => 200, 'msg' => '操作成功',"data"=>[]]);

        }catch(\Exception $e){

            return json()->data(['code'=>$e->getCode(),"msg"=>$e->getMessage()]);
        }
    }

    /**
     * @return \think\response\Json
     */
    public function creditListsAction()
    {
        try {
            if (!$this->user) {
                throw new \Exception('请先登录', 401);
            }

            $params['where'][] = ['userId', '=', $this->user->userId];
            $params['order'] = ['recordId' => 'desc'];
            $lists = $this->app->userService->getCreditLists($params, $this->page);

            $data['lists'] = [];

            if (count($lists)) {
                foreach ($lists as $key => $val) {
                    $data['lists'][] = [
                        'recordId' => $val->recordId,
                        'userId' => $val->userId,
                        'originCredit' => $val->originCredit,
                        'changeCredit' => $val->changeCredit,
                        'finalCredit' => $val->finalCredit,
                        'remark' => $val->remark,
                        'createdAt' => $val->createdAt
                    ];
                }
            }

            $data['totalInfo'] = $this->app->utilService->getMeta($lists);

            return json(['code' => 200, 'msg' => '查询成功', 'data'=> $data]);
        }catch(\Exception $e){
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }

    /**
     * @return \think\response\Json
     */
    public function donateListsAction()
    {
        try {
            if (!$this->user) {
                throw new \Exception('请先登录', 401);
            }

            $params['where'][] = ['userId', '=', $this->user->userId];
            $params['order'] = ['userDonateId' => 'desc'];
            $lists = $this->app->userService->getDonateLists($params, $this->page);

            $data['lists'] = [];

            if (count($lists)) {
                foreach ($lists as $key => $val) {
                    $data['lists'][] = [
                        'userDonateId' => $val->userDonateId,
                        'userId' => $val->userId,
                        'organizationId' => $val->organizationId,
                        'organizationName' => $val->organization->organizationName,
                        'organizationLogo' => $val->organization->organizationLogo,
                        'donateCredit' => $val->donateCredit,
                        'createdAt' => $val->createdAt
                    ];
                }
            }

            $data['totalInfo'] = $this->app->utilService->getMeta($lists);

            return json(['code' => 200, 'msg' => '查询成功', 'data'=> $data]);
        }catch(\Exception $e){
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }

    /**
     * 获取用户答题列表
     * @param $id
     * @return \think\response\Json
     */
    public function answerListsAction()
    {
        try {
            if (!$this->user) {
                throw new \Exception('请先登录', 401);
            }

            $params['where'][] = ['userId', '=', $this->user->userId];
            $params['order'] = ['userAnswerId' => 'desc'];
            $lists = $this->app->userService->getAnswerLists($params, $this->page);

            $data['lists'] = [];

            if (count($lists)) {
                foreach ($lists as $key => $val) {
                    $data['lists'][] = [
                        'userAnswerId' => $val->userAnswerId,
                        'userId' => $val->userId,
                        'questionId' => $val->questionId,
                        'questionTitle' => $val->question->questionTitle,
                        'answer' => $val->answer,
                        'isRight' => $val->isRight,
                        'credit' => $val->credit,
                        'createdAt' => $val->createdAt
                    ];
                }
            }

            $data['totalInfo'] = $this->app->utilService->getMeta($lists);

            return json(['code' => 200, 'msg' => '查询成功', 'data'=> $data]);
        }catch(\Exception $e){
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }

    public function getPhoneAction()
    {
        try {
            if (!$this->user) {
                throw new \Exception('请先登录', 401);
            }

            $wxprogram = Wxprograms::find($this->appletId);
            $appId = $wxprogram->appId;

            $wxdata = new WxDataCrypt($appId, $this->post['sessionKey']);
            $errCode = $wxdata->decryptData($this->post['encryptedData'], $this->post['iv'], $data );
            if ($errCode !== 0) {
                throw new \Exception("sessionKey过期");
            }
            $resData = json_decode($data,true);
            $update = [
                'phone' => $resData['purePhoneNumber'],
                'countryCode' => $resData['countryCode']
            ];
            $this->app->userService->update($this->user, $update);

            return json(['code' => 200, 'msg' => '授权成功', 'data'=> ['phone' => $resData['purePhoneNumber']]]);
        }catch(\Exception $e){
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }
}